package com.jin.webvideo.externalInterfaces.iqiyi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jin.webvideo.exception.UnavailableServiceException;
import com.jin.webvideo.externalInterfaces.PlatformSupport;
import com.jin.webvideo.externalInterfaces.entity.*;
import com.jin.webvideo.util.base.StringUtil;
import com.jin.webvideo.util.base.URLUtil;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Component
public class IQIYIVideoInfoHandler{
    //%ID%=90927301;
    private static final String VIDEOINFO_URL = "https://pub.m.iqiyi.com/h5/main/videoList/album/?albumId=%ID%&size=%pageSize%&page=%page%&needPrevue=true&needVipPrevue=false&callback=a";
    //894482000
    private  static final String BASE_URL = "https://pcw-api.iqiyi.com/video/video/baseinfo/%id%?t=%time%&callback=a";

    private  static final String VIDEOINFO_EXT_URL = "https://pcw-api.iqiyi.com/album/source/svlistinfo?cid=6&sourceid=%s&timelist=%s&callback=a";
    public Filmography baseInfo(String docid, String id) throws IOException, UnavailableServiceException {
        if (id.isEmpty()){
            id = docid;
        }
        String url = URLUtil.format(BASE_URL, id, String.valueOf(System.currentTimeMillis()));
        Result result = IQIYIUtil.readResult(url, 6, -13);
        if ( !StringUtil.isEmpty( result.getData() )){
            JSONObject object = JSONObject.parseObject( result.getData() );
            return toFilmography(object);
        }
        return new Filmography();
    }
    public Filmography toFilmography(JSONObject obj ){
        Filmography filmography = new Filmography();
        filmography.setDesc( obj.getString("description") );
        filmography.setName( obj.getString("albumName") );
        filmography.setId( obj.getString("albumId") );
        filmography.setUrl( obj.getString("playUrl") );
        filmography.setPlatformName(PlatformSupport.PLATFORM_NAME_IQIYI);
        filmography.setPlatform(PlatformSupport.PLATFORM_IQIYI);
        return filmography;
    }

    public List<FilmographyInfo> videoInfos(String docid, String id, String pageSize, String page) throws Exception {
        List<FilmographyInfo> infos = new ArrayList<>();
        String url = URLUtil.format(VIDEOINFO_URL, docid, pageSize, page);
        Result result  = IQIYIUtil.readResult(url, 2, -1);
        if ( !StringUtil.isEmpty(result.getData()) ){
            JSONObject jsonObject = JSONObject.parseObject(result.getData());
            JSONArray videos = jsonObject.getJSONArray("videos");
            infos = toList(videos);
        }
        if (infos.size() == 0){
            url = String.format(VIDEOINFO_EXT_URL, docid, year());
            result  = IQIYIUtil.readResult(url, 6, -13);
            if (!StringUtil.isJson(result.getData())){
                return infos;
            }
            JSONObject jsonObject = JSONObject.parseObject(result.getData());
            infos = extList(jsonObject);
        }
        return infos;
    }
    public List<FilmographyInfo> toList(JSONArray videos){
        List<FilmographyInfo> infos = new ArrayList<>();
        if (null == videos){
            return infos;
        }
        for (int i = 0, l = videos.size(); i < l; i ++){
            JSONObject video = videos.getJSONObject(i);
            String type = video.getString("type");
            if (null != type && type.equals("3")){
                continue;
            }
            FilmographyInfo filmographyInfo = new FilmographyInfo();
            filmographyInfo.setDesc(video.getString("desc"));
            filmographyInfo.setId(video.getString("id"));
            filmographyInfo.setNumber(video.getInteger("pd"));
            filmographyInfo.setPlatform(PlatformSupport.PLATFORM_IQIYI);
            String url = video.getString("pageUrl");
            filmographyInfo.setUrl(format(url));
            filmographyInfo.setTitle(video.getString("subTitle"));
            if (filmographyInfo.getTitle().length() > 4){
                filmographyInfo.setDisplayMode(FilmographyInfo.DISPLAY_MODE_TITLE_BLOCK);
            }
            filmographyInfo.setImg(video.getString("qualityImageUrl"));
            infos.add(filmographyInfo);
        }
        return infos;
    }
    private String format(String url)  {
        int index = url.indexOf("//");
        if (index!=-1){
            String p = url.substring(0, index + 2);
            if (p.length() == 2){
                p = "https:"+p;
            }
            String host = url.substring(index + 2);
            if (host.startsWith("m")){
                host = host.replaceFirst("m", "www");
            }
            url = p + host;
        }
        return url;
    }
    private List<FilmographyInfo> extList(JSONObject data){
        Calendar calendar = Calendar.getInstance();
        StringBuilder builder = new StringBuilder();
        int year = calendar.get(Calendar.YEAR);
        int startYear = Math.min(2015, year);
        List<FilmographyInfo> infos = new ArrayList<>();

        while (startYear <= year){
            String key = String.valueOf(startYear);
            List<FilmographyInfo> infoList = toList2(data.getJSONArray(key));
            infos.addAll(infoList);
            startYear ++;
        }
        int i = 1;
        for (FilmographyInfo info : infos){
            info.setNumber(i++);
            if (info.getTitle().length() > 5){
                info.setDisplayMode(FilmographyInfo.DISPLAY_MODE_TITLE_BLOCK);
            }
        }
        return infos;
    }
    private List<FilmographyInfo> toList2(JSONArray data){
        List<FilmographyInfo> infos = new ArrayList<>();
        for (int i = data.size() - 1; i >= 0 ; i--){
            JSONObject obj = data.getJSONObject(i);
            FilmographyInfo info = new FilmographyInfo();
            info.setId(obj.getString("tvId"));
            info.setTitle(obj.getString("subtitle"));
            info.setImg(obj.getString("imageUrl"));
            info.setDesc(obj.getString("description"));
            info.setUrl(obj.getString("playUrl"));
            info.setPlatform(PlatformSupport.PLATFORM_IQIYI);
            info.setDate(obj.getString("period"));
            infos.add(info);
        }
        return infos;
    }
    private String year(){
        Calendar calendar = Calendar.getInstance();
        StringBuilder builder = new StringBuilder();
        int year = calendar.get(Calendar.YEAR);
        int startYear = Math.min(2015, year);
        while (startYear <= year){
            builder.append(startYear);
            builder.append(",");
            startYear ++;
        }
        return builder.substring(0, builder.length() - 1);
    }
}
